﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;


namespace ChatApplication.Models
{
    public class Chat
    {
        private readonly static Lazy<Chat> _instance = new Lazy<Chat>(
            () => new Chat(GlobalHost.ConnectionManager.GetHubContext<ChatHub>().Clients));

        public static List<Client> Clients = new List<Client>();
        private IHubConnectionContext iHubConnectionContext;

        public Chat(IHubConnectionContext iHubConnectionContext)
        {
            // TODO: Complete member initialization
            this.ConnectionContext = (IHubConnectionContext)iHubConnectionContext;
        }
        
        public static Chat Instance
        {
            get
            {
                return _instance.Value;
            }
        }

        public IHubConnectionContext ConnectionContext
        {
            get;
            set;
        }

       

        public void SpreadMessage(string message)
        {
            BroadCastMessage(message);
        }

        private void BroadCastMessage(string message)
        {
            ConnectionContext.All.newMessage(message);
            
        }

        public void GetClients()
        {
            System.Web.Script.Serialization.JavaScriptSerializer oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            string sJSON = oSerializer.Serialize(Clients);

            ConnectionContext.All.userList(sJSON);
        }
    }
}